package com.kaifamiao.schedule;

/**
 * 1、private volatile boolean interrupted 是线程`中断状态` (国内资料可能称作`中断标志`)
 *      Interrupt state of the thread (线程的中断状态)
 *      read/written directly by JVM ( 由JVM直接读写 )
 * 2、public void interrupt() 中断线程 并 修改中断状态 (interrupted)
 * 3、public boolean isInterrupted() 返回中断标志 (不修改中断状态)
 * 4、public static boolean interrupted() 返回中断标志 并 清除中断状态 (即重置中断状态)
 */
public class InterruptTest {

    public static void main(String[] args) throws InterruptedException {

        // 创建线程
        Thread t = new Thread( () -> {
            Thread current = Thread.currentThread();
            String name = current.getName();
            System.out.printf("%s begin\n", name);
            try {
                System.out.println( name + " 即将睡眠" );
                Thread.sleep(1000L * 60 * 60 * 24 );
                System.out.println( name + " 已经睡醒" );
            } catch ( InterruptedException e ) {
                System.out.println( name + " 睡眠被中断" );
                System.out.println( "message: " + e.getMessage() );
                System.out.println( "interrupted: " + current.isInterrupted() );
            }
            System.out.printf("%s end\n", name);
        }, "睡佛");

        // 启动线程
        t.start();

        System.out.println( "main: t.interrupted = " + t.isInterrupted() );

        Thread.sleep( 1000L );
        // main 调用 t 的 interrupt 方法
        t.interrupt();
        System.out.println( "main: t.interrupted = " + t.isInterrupted() );

        Thread.sleep( 1000L );
        System.out.println( "main: t.interrupted = " + t.isInterrupted() );
    }

}
